package com.defysoft.waukids.attend;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Type.BC_ATTEND;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.R;

public class Attend_SelectDay_A extends BaseActivity implements OnClickListener {

	Calendar calendar;
	Calendar preCalendar;
	GridView gridView;
	String[] day = { "일", "월", "화", "수", "목", "금", "토", "", "", "", "", "", "",
			"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
			"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
			"", "" };
	int nowcount;
	int month = 0;
	ArrayList<BC_ATTEND> list;
	Toolbar toolbar;

	final int FAIR_GETLIST = 9;
	final int SUCCESS_GETLIST = 10;
	String photo = "";
	String stu_code;
	String stu_name;
	TextView tv;
	WebView wv;
	View view[] = new View[2];

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg1 == ATTEND_SELECTDAY_DETAIL_UPDATE_INSERT) {
			setStartData();
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_attend__select_day_);
		setStartData();
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public void setStartData() {
		super.setStartData();
		stu_code = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_PK_STU_CODE);
		stu_name = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_STU_NAME);
		((TextView) findViewById(R.id.ATTENDSELECTDAY_NAME)).setText(stu_name
				+ " 의\n출석부");
		wv = (WebView) findViewById(R.id.ATTENDSELECTDAY_IMG);
		wv.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startActivity(new Intent(Attend_SelectDay_A.this,
							Attend_SelectDay_Photo_A.class).putExtra("photo",
							PublicConstant.URI_STUDENDPHOTO + photo));
					break;
				}
				return false;
			}
		});

		tv = (TextView) findViewById(R.id.ATTENDSELECTDAY_NOWTIME);
		view[0] = findViewById(R.id.ATTENDSELECTDAY_BACK);
		view[1] = findViewById(R.id.ATTENDSELECTDAY_NEXT);
		view[0].setOnClickListener(this);
		view[1].setOnClickListener(this);
		gridView = (GridView) findViewById(R.id.ATTENDSELECTDAY_GRID);
		toolbar = (Toolbar) findViewById(R.id.ATTENDSELECTDAY_TOOL);

		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		startNetwork(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 1:
					mainThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ATTENDSELECTDAY_BACK:
			month--;
			startNetwork(1);
			break;
		case R.id.ATTENDSELECTDAY_NEXT:
			month++;
			startNetwork(1);
			break;
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // 0번은 꼭 try catch의 오류수정코드
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
					.show();
			break;
		case FAIR_GETLIST: // 1번은 꼭 서버에러코드 출력으로
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("리스트 갱신실패", (String) _message.obj, 0);
			break;
		case SUCCESS_GETLIST:

			if (firstThread != null) {
				firstThread.interrupt();
			}
			wv.setVerticalScrollBarEnabled(false);
			wv.setVerticalScrollbarOverlay(false);
			wv.setHorizontalScrollBarEnabled(false);
			wv.setHorizontalScrollbarOverlay(false);
			wv.setInitialScale(100);

			if (photo == null || photo.length() < 5) {// 이미지 파일이 없으면 앱내에서 지정된
														// 이미지를 뿌려주고
				wv.setBackgroundColor(0);
				wv.setBackgroundResource(R.drawable.perm_group_personal_info);
			} else {// 이미지 파일이 있으면
				wv.loadDataWithBaseURL(null,
						creHtmlBody(PublicConstant.URI_STUDENDPHOTO + photo),
						"text/html", "utf-8", null);
			}
			setCalendar();
			break;
		}
	}

	public void setCalendar() {

		nowcount = 7;

		preCalendar = Calendar.getInstance();

		preCalendar.set(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH) - 1, 1);
		tv.setText(calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1));
		int rest = calendar.get(Calendar.DAY_OF_WEEK) - 1;

		int prerest = preCalendar.getActualMaximum(preCalendar.DATE) - rest + 1;
		for (; nowcount - 7 < rest; nowcount++) {
			day[nowcount] = prerest + (nowcount - 7) + "00";
		}
		for (int i = 1; i <= calendar.getActualMaximum(calendar.DATE); i++, nowcount++) {
			day[nowcount] = i + "";
		}
		for (int i = 1; nowcount < day.length; nowcount++, i++) {
			day[nowcount] = i + "00";
		}
		gridView.setAdapter(new DayAdapter());
		endDIal();
	}

	public void mainThread() {
		String msg = "";
		try {
			calendar = Calendar.getInstance();
			calendar.set(calendar.get(Calendar.YEAR),
					calendar.get(Calendar.MONTH) + month, 1);
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SELECT_ATTEND_MONTHLIST, "stu_code=" + stu_code
							+ "&year=" + (calendar.get(Calendar.YEAR))
							+ "&month=" + (calendar.get(Calendar.MONTH) + 1)));
			if (jsonObject.getBoolean("success")) {
				photo = jsonObject.getString("photo");
				msg = jsonObject.getString("payload");
				if (msg != null) {
					list = JsonParser.AttendSelectList(msg);
				} else {
					list = null;
				}
				onNetworkCallback(SUCCESS_GETLIST, msg);
			} else {
				onNetworkCallback(FAIR_GETLIST, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	class DayAdapter extends ArrayAdapter<String> {
		public DayAdapter() {
			super(Attend_SelectDay_A.this, 0);
		}

		@Override
		public int getCount() {
			return day.length;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView holder;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.attendselectday_row, null);
				int width = ((gridView.getWidth()) / 7);
				int height = ((gridView.getWidth()) / 7);

				(convertView.findViewById(R.id.ATTENDSELECTDAY_LL))
						.setLayoutParams(new LinearLayout.LayoutParams(width,
								height));
				holder = (TextView) convertView
						.findViewById(R.id.ATTENDSELECTDAY_ITEMTV);
				convertView.setTag(holder);

			} else {
				holder = (TextView) convertView.getTag();
			}
			holder.setBackgroundColor(0x00000000);
			holder.setText("");
			holder.setOnClickListener(null);
			if (position > 6 && Integer.parseInt(day[position]) >= 100) {
				holder.setTextColor(0xffaaaaaa);
				holder.setText((Integer.parseInt(day[position]) / 100) + "");
			} else {
				if (position % 7 == 0) {
					holder.setTextColor(0xffFF0000);
				} else if (position % 7 == 6) {
					holder.setTextColor(0xff0054FF);
				} else {
					holder.setTextColor(0xff000000);
				}
				holder.setText(day[position]);
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).Att_Date.split("-")[2]
								.equals(day[position])) {
							if (position % 7 != 0 && position % 7 != 6) {
								holder.setText("");

								if (list.get(i).Att_Check == 0) {
									holder.setBackgroundResource(R.drawable.at_on);
								} else {
									holder.setBackgroundResource(R.drawable.at_off);
								}
							}

						}
					}// ForEnd
				}// ifEnd
				if (position > 6) {
					final int pos = position;
					holder.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							startActivityForResult(
									new Intent(Attend_SelectDay_A.this,
											Attend_Detail_A.class)
											.putExtra(
													INTENT_EXTRA_ATTEND_PK_STU_CODE,
													stu_code)
											.putExtra(
													INTENT_EXTRA_ATTEND_STU_NAME,
													stu_name)
											.putExtra("photo", photo)
											.putExtra(
													INTENT_EXTRA_ATTEND_DATE,
													calendar.get(Calendar.YEAR)
															+ "-"
															+ ((calendar
																	.get(Calendar.MONTH) + 1)
																	+ "-" + day[pos])),
									0);
						}
					});
					convertView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							startActivityForResult(
									new Intent(Attend_SelectDay_A.this,
											Attend_Detail_A.class)
											.putExtra(
													INTENT_EXTRA_ATTEND_PK_STU_CODE,
													stu_code)
											.putExtra(
													INTENT_EXTRA_ATTEND_STU_NAME,
													stu_name)
											.putExtra(
													INTENT_EXTRA_ATTEND_DATE,
													calendar.get(Calendar.YEAR)
															+ "-"
															+ ((calendar
																	.get(Calendar.MONTH) + 1)
																	+ "-" + day[pos])),
									0);
						}
					});
				}
			}// elseEnd
			return convertView;
		}
	}

	public String creHtmlBody(String imagUrl) {
		StringBuffer sb = new StringBuffer("<HTML>");
		sb.append("<HEAD>");
		sb.append("</HEAD>");
		sb.append("<BODY  style='margin: 0; padding: 0'>");
		sb.append("<img width=\"100%\" height=\"100%\" src=\"" + imagUrl
				+ "\">");
		sb.append("</BODY>");
		sb.append("</HTML>");

		return sb.toString();
	}
}
